package net.ewon.avatar.agent.impl;

import static java.nio.file.FileVisitResult.CONTINUE;

import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class LinkFiles extends SimpleFileVisitor<Path> {

	private final Path source;
	private final Path target;
	private Path currentSourceDir;
	private Path currentTargetDir;

	public LinkFiles(Path source, Path target) {
		this.source = source;
		this.target = target;
	}

	@Override
	public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
			throws IOException {
		currentSourceDir = dir;
		currentTargetDir = target.resolve(source.relativize(dir)); 
		try {
			Files.createDirectory(currentTargetDir);
		} catch (FileAlreadyExistsException e) {
			// ignore
		}

		return CONTINUE;
	}

	@Override
	public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
			throws IOException {
		Path targetFile = currentTargetDir.resolve(currentSourceDir.relativize(file));
		try {
			Files.createSymbolicLink(targetFile, file);
		} catch (FileAlreadyExistsException e) { 
			// ignore
		}
		return CONTINUE;
	}

}
